<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Mars3D 天地图 Demo</title>
    <style>
      body,
      html {
        margin: 0;
        padding: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
      #mars3d-container {
        width: 100%;
        height: 100%;
      }
    </style>
    <!-- 引入 Mars3D 库 -->
    <script src="https://cdn.jsdelivr.net/npm/mars3d@latest/dist/mars3d.min.js"></script>
  </head>
  <body>
    <div id="mars3d-container"></div>

    <script>
      // 初始化 Mars3D 场景
      const mars = new Mars3D.Mars3D("mars3d-container", {
        scene: {
          center: { lng: 119.4, lat: 33.0, alt: 10000, heading: 0, pitch: -45 },
          baseLayerPicker: false,
          timeline: false,
          animation: false,
          shouldAnimate: false,
          skyAtmosphere: false,
        },
        layers: [
          {
            layer: "tianditu",
            type: "vector",
            key: "0ae8ed20bc75ab1e50aed5c12bdac0d4",
            style: {
              stroke: true,
              color: "#0000FF",
              weight: 2,
              opacity: 0.8,
              fillOpacity: 0.5,
            },
          },
        ],
      });

      // 加载宝应县的边界数据
      function loadBoundaryData() {
        fetch(
          `https://api.tianditu.gov.cn/adminregion?tk=0ae8ed20bc75ab1e50aed5c12bdac0d4&postStr={"type":"getSubdivisions","admCode":"321023"}`
        )
          .then((response) => response.json())
          .then((data) => {
            if (data.status === 0) {
              const boundaries = data.data[0].boundaries;
              const coordinates = boundaries.map((boundary) =>
                boundary.split(";").map((point) => point.split(",").map(Number))
              );

              const polygon = new Cesium.PolygonGraphics({
                hierarchy: new Cesium.PolygonHierarchy(
                  Cesium.Cartesian3.fromDegreesArray(coordinates[0])
                ),
                material: Cesium.Color.BLUE.withAlpha(0.5),
                outline: true,
                outlineColor: Cesium.Color.BLACK,
              });

              const entity = mars.scene.primitives.add(
                new Cesium.Entity({
                  polygon: polygon,
                })
              );

              // 设置视图以适应宝应县的边界
              mars.scene.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(119.4, 33.0, 10000),
              });
            } else {
              console.error("请求失败:", data.message);
            }
          })
          .catch((error) => {
            console.error("请求出错:", error);
          });
      }

      // 初始化地图后加载边界数据
      mars.on(Mars3D.EventMapReady, () => {
        loadBoundaryData();
      });
    </script>
  </body>
</html>
